<template>
    <div :class="Data.tabName == 2 ? 'deep_change page' : 'page'">
        <el-tabs v-model="Data.tabName" @tab-click="tabClick">
            <el-tab-pane label="分销员列表" :name="1">
                <div>
                    <div class="search-form zw-form-layout">
                        <el-form ref="formRef" :model="searchForm" label-width="auto">
                            <el-row :gutter="24">
                                <el-col :span="8">
                                    <el-form-item label="分销员" prop="distributor">
                                        <el-input
                                            v-model="searchForm.distributor"
                                            placeholder="请输入昵称、手机号、ID查询"
                                            clearable></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="邀请人" prop="inviter">
                                        <el-input
                                            v-model="searchForm.inviter"
                                            placeholder="输入邀请人的昵称、手机号、ID查询"
                                            clearable></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="来源店铺" prop="shopId">
                                        <el-select
                                            v-model="searchForm.shopId"
                                            filterable
                                            reserve-keyword
                                            clearable
                                            placeholder="全部店铺">
                                            <el-option label="全部店铺" value="" />
                                            <el-option
                                                v-for="item in shopList"
                                                :key="item.shopId"
                                                :label="item.shopName"
                                                :value="item.shopId" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="邀请人" prop="inviterType">
                                        <el-select v-model="searchForm.inviterType" clearable placeholder="不限">
                                            <el-option label="不限" value="" />
                                            <el-option label="总部" :value="1" />
                                            <el-option label="分销员" :value="2" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="加入时间" prop="createdAt">
                                        <el-date-picker
                                            v-model="createdAt"
                                            type="daterange"
                                            range-separator="至"
                                            start-placeholder="开始日期"
                                            end-placeholder="结束日期" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8" class="zw-form-btns">
                                    <el-button type="primary" @click="searchHandler">查询</el-button>
                                    <el-button plain @click="resetHandler">清空</el-button>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                    <el-row>
                        <el-col class="zw-table-btns">
                            <el-button v-auth="'distribution_members:add'" type="primary" @click="showDialog(1)">
                                新增分销员
                            </el-button>
                            <el-button v-auth="'distribution_members:import'" @click="showDialog(3)">
                                批量导入分销员
                            </el-button>
                        </el-col>
                    </el-row>
                    <el-table :data="Data.tableData" border>
                        <el-table-column align="center" min-width="120" prop="" label="分销员">
                            <template v-slot="{ row }">
                                <div v-if="row.dtbNickname">{{ row.dtbNickname }}</div>
                                <div v-if="row.dtbMobile">{{ row.dtbMobile }}</div>
                                <div v-if="row.dtbUid">{{ row.dtbUid }}</div>
                            </template>
                        </el-table-column>
                        <!-- 没有邀请人显示 ‘-’ -->
                        <el-table-column align="center" min-width="120" prop="" label="邀请人">
                            <template v-slot="{ row }">
                                <div>
                                    <div v-if="row.inviterNickname">{{ row.inviterNickname }}</div>
                                    <div v-if="row.inviterMobile">{{ row.inviterMobile }}</div>
                                    <div v-if="row.inviterUid">{{ row.inviterUid }}</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="level.levelName" label="等级"> </el-table-column>
                        <el-table-column align="center" prop="totalFans" label="粉丝数">
                            <template #default="{ row }">{{ row.totalFans || 0 }}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="totalInvite" label="邀请数">
                            <template #default="{ row }">{{ row.totalInvite || 0 }}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="totalSales" label="累计业绩">
                            <template #default="{ row }">￥{{ Number(row.totalSales) || 0 }}</template>
                        </el-table-column>
                        <el-table-column align="center" prop="totalBrokerage" label="累计收益">
                            <template #default="{ row }">
                                <span v-if="row.totalBrokerageCash">￥{{ row.totalBrokerageCash || 0 }}</span
                                ><span v-if="row.totalBrokerageCash && row.totalBrokerage">+</span
                                ><span v-if="row.totalBrokerage">{{ Number(row.totalBrokerage) || 0 }}积分</span
                                ><span v-if="!row.totalBrokerageCash && !row.totalBrokerage">0</span>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="countingBrokerage" label="待结算收益">
                            <template #default="{ row }">
                                <span v-if="row.countingBrokerageCash">￥{{ row.countingBrokerageCash }}</span
                                ><span v-if="row.countingBrokerageCash && row.countingBrokerage">+</span
                                ><span v-if="row.countingBrokerage">{{ Number(row.countingBrokerage) || 0 }}积分</span
                                ><span v-if="!row.countingBrokerageCash && !row.countingBrokerage">0</span>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" width="110" prop="joinAt" label="加入时间"> </el-table-column>
                        <el-table-column align="center" prop="shopName" label="来源店铺"> </el-table-column>
                        <el-table-column align="center" prop="statusName" label="状态">
                            <template #default="{ row }">
                                <span v-if="row.status == 2" class="common"></span>
                                <span v-if="row.status == 3" class="error"></span>
                                {{ row.statusName }}
                            </template>
                        </el-table-column>
                        <el-table-column align="center" fixed="right" label="操作">
                            <template #default="{ row }">
                                <div>
                                    <el-button
                                        size="small"
                                        v-show="row.status == 2 || row.status == 3"
                                        v-auth="'distribution_members:set'"
                                        @click.stop="showDialog(2, row)">
                                        设置
                                    </el-button>
                                </div>
                                <div>
                                    <el-button
                                        size="small"
                                        v-auth="'distribution_members:remove'"
                                        v-show="row.status == 1"
                                        @click.stop="deleteHandler(row)">
                                        删除
                                    </el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination zw-pagination">
                        <Pagination
                            :total="Data.totalCount"
                            :page-size="searchForm.perPage"
                            :current-page="searchForm.page"
                            @size-change="onSizeChange"
                            @pageChange="pageChange" />
                    </div>
                </div>
            </el-tab-pane>
            <el-tab-pane label="等级管理" :name="2">
                <level
                    v-if="checkPermission('distribution_members:level_view')"
                    :inviteSwitch="Data.inviteSwitch"
                    :levelList="levelList"></level>
                <div class="none" v-else>没有页面查看权限，请前往账号管理页面配置</div>
            </el-tab-pane>
        </el-tabs>

        <el-dialog destroy-on-close v-model="dialog.visible" :title="dialog.title" width="50%">
            <el-form ref="dialogForm" :model="dialogFormData" :rules="rules" label-width="80px">
                <div v-if="dialog.type === 1">
                    <el-form-item label="手机号" prop="phone">
                        <el-input style="width: 50%" v-model="dialogFormData.phone" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="分销等级" prop="levelId">
                        <el-select style="width: 50%" v-model="dialogFormData.levelId">
                            <el-option
                                v-for="item in levelList"
                                :key="item.id"
                                :label="item.levelName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <!-- 没开启邀请佣金，不展示该行  -->
                    <el-form-item v-if="Data.inviteSwitch == 2" label="邀请人" prop="type">
                        <el-radio-group @change="inviterTypeChange" v-model="dialogFormData.type">
                            <el-radio :label="1">总部</el-radio>
                            <el-radio :label="2">
                                非总部 &ensp;
                                <span v-if="dialogFormData.type === 2">
                                    <el-button @click="showInviterList">选择</el-button>
                                    <span v-if="dialogFormData.inviterName"
                                        >&ensp;已选择： {{ dialogFormData.inviterName }}
                                        <span>({{ dialogFormData.inviterPhone }})</span>
                                    </span>
                                </span>
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>
                <div v-else-if="dialog.type === 2">
                    <el-form-item label="状态" prop="status">
                        <el-radio-group v-model="dialogFormData.status">
                            <el-radio :label="2">正常</el-radio>
                            <el-radio :label="3">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="等级" prop="levelId">
                        <el-select style="width: 50%" v-model="dialogFormData.levelId">
                            <el-option
                                v-for="item in levelList"
                                :key="item.id"
                                :label="item.levelName"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <!-- 判断是否开启邀请佣金  -->
                    <el-form-item label="邀请人">
                        <span> {{ dialogFormData.inviterName || '-' }}</span>
                        <span v-if="dialogFormData.inviterPhone">({{ dialogFormData.inviterPhone }})</span>
                        <span v-if="Data.inviteSwitch == 2" class="link_btn" @click="showInviterType">修改</span>
                    </el-form-item>
                </div>
                <div v-else-if="dialog.type === 3">
                    <el-upload
                        :headers="headers"
                        :action="constants.TEMPLATE_UPLOAD_URL"
                        :show-file-list="false"
                        :on-success="uploadSuccessHandler">
                        <el-button type="primary">选择文件</el-button>
                        <span class="template" @click.stop="downLoadTemplate">下载模板</span>
                        <template #tip>
                            <div class="upload_tip">仅支持xlsx、xls格式，不超过2M</div>
                        </template>
                    </el-upload>
                    <div v-if="dialogFormData.ossFileName" class="upload_file">
                        <el-icon><Document /></el-icon>&ensp;{{ dialogFormData.ossFileName }}
                    </div>
                </div>
            </el-form>
            <el-dialog v-model="dialog.inviterTypeVisible" width="40%" title="修改邀请人" append-to-body>
                <el-form ref="dialog2Form" :model="dialogFormData" :rules="rules" label-width="80px">
                    <el-form-item label="原邀请人">
                        {{ dialogFormData.orginInviterName }}
                        <span v-if="dialogFormData.orginInviterPhone"> ({{ dialogFormData.orginInviterPhone }}) </span>
                    </el-form-item>
                    <el-form-item label="新邀请人" prop="type">
                        <el-radio-group @change="inviterTypeChange" v-model="dialogFormData.type">
                            <el-radio :label="1">总部</el-radio>
                            <el-radio :label="2">
                                非总部 &ensp;
                                <span v-if="dialogFormData.type === 2">
                                    <el-button @click="showInviterList">选择</el-button>
                                    <span v-if="dialogFormData.inviterId"
                                        >&ensp;已选择： {{ dialogFormData.inviterName }}
                                        <span v-if="dialogFormData.inviterPhone">
                                            ({{ dialogFormData.inviterPhone }})
                                        </span>
                                    </span>
                                </span>
                            </el-radio>
                            <label v-if="dialogFormData.type === 2 && dialogFormData.inviterId"
                                >&ensp;已选择： {{ dialogFormData.inviterName }}
                                <span v-if="dialogFormData.inviterPhone"> ({{ dialogFormData.inviterPhone }}) </span>
                            </label>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="cancelInviterTypeDialog">取消</el-button>
                        <el-button type="primary" @click="comfirmInviterTypeDialog">保存</el-button>
                    </span>
                </template>
            </el-dialog>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialog.visible = false">取消</el-button>
                    <el-button type="primary" @click="comfirmHandler">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <ZwChooseInviter @selectHandler="selectInviter" :selectId="dialogFormData.inviterId" ref="chooseInviter" />
    </div>
</template>

<script setup name="">
import { ref, reactive, inject, onMounted, onUnmounted, computed, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { format, dealObjectEmptyValue, downloadImgHandler, checkPermission, isMobile } from '@/commons/utils.js';
import { ZwMessage } from '@/commons';
import constants from '@/commons/constants';
import request from '@/request';
import Pagination from '@/components/Pagination.vue';
import { ElMessage } from 'element-plus';
import storage from '@/commons/storage';
import { getShopListHook } from '@/hooks';
import level from './level.vue';
const confirm = inject('confirm');
const headers = reactive({
    'ZW-PLATFORM-TOKEN': storage.get('ZW-TOKEN'),
    'ZW-TENANT-ID': storage.get('ZW-TENANT-ID')
});
const chooseInviter = ref(null);
const formRef = ref(null);
const dialogForm = ref(null);
const dialog2Form = ref(null);
let shopList = reactive([]);
let levelList = reactive([]);
const searchForm = reactive({
    distributor: '', //分销员关键字（ID、手机号、昵称）
    inviter: '', //邀请人关键字（ID、手机号、昵称）
    shopId: '',
    joinAtStart: '',
    joinAtEnd: '',
    inviterType: '', //邀请人类型（1-总部 2-分销员）
    page: 1, //当前页
    perPage: 10 //每页展示条数
});
const Data = reactive({
    tabName: 1,
    totalCount: 1,
    tableData: [],
    // 邀请佣金开关 1-关闭 2-开启
    inviteSwitch: 1
});
const dialog = reactive({
    visible: false,
    inviterTypeVisible: false,
    type: 1,
    title: ''
});
const dialogFormData = reactive({
    id: '',
    phone: '',
    type: 1,
    inviterId: '',
    inviterName: '',
    inviterPhone: '',
    orginInviterPhone: '',
    orginInviterName: '',
    status: '',
    levelId: '',
    ossFileName: '',
    ossFileObj: {}
});

// 自定义表单校验
const validateFields = ({ field }, value, callback) => {
    switch (field) {
        case 'type':
            if (dialogFormData.type === 1) {
                callback();
            }
            if (dialogFormData.type === 2 && dialogFormData.inviterId) {
                callback();
            }
            callback(new Error('请选择邀请人'));
            break;
        case 'phone':
            if (isMobile(value)) {
                callback();
            } else {
                callback(new Error('请输入正确的手机号!'));
            }
            break;
        default:
            break;
    }
};
const rules = reactive({
    phone: [
        { required: true, message: '请填写手机号', trigger: 'blur' },
        { validator: validateFields, trigger: 'blur' }
    ],
    status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
    levelId: [{ required: true, message: '请选择等级', trigger: 'blur' }],
    type: [
        { validator: validateFields, trigger: 'blur' },
        { required: true, message: '请选择邀请人', trigger: 'blur' }
    ]
});

const createdAt = computed({
    get() {
        return [searchForm.joinAtStart, searchForm.joinAtEnd];
    },
    set(val) {
        if (val) {
            searchForm.joinAtStart = format(val[0], 'YYYY-MM-DD HH:mm:ss');
            searchForm.joinAtEnd = format(val[1], 'YYYY-MM-DD 23:59:59');
        } else {
            searchForm.joinAtStart = '';
            searchForm.joinAtEnd = '';
        }
    }
});

// 获取来源店铺
const getshopList = async () => {
    const { data } = await getShopListHook();
    shopList.length = 0;
    const list = data.list;
    Object.assign(shopList, list);
};

// 获取等级列表
const getLevelList = async () => {
    const { data } = await request('queryDistributorLevelListServ');
    levelList.length = 0;
    const list = data.list;
    Object.assign(levelList, list);
};

const getMemberList = async () => {
    const { data } = await request('queryDistributorListServ', searchForm);
    const { list } = data;
    Data.tableData.length = 0;
    Data.tableData.push(...(list || []));
    Data.totalCount = data?.totalCount;
};
const tabClick = ({ paneName }) => {
    if (paneName == 1) {
        // searchForm.page = 1;
        setTimeout(() => {
            // getMemberList();
            getLevelList();
        });
    }
};
const resetHandler = () => {
    formRef.value.resetFields();
    createdAt.value = '';
};
const pageChange = pageNum => {
    searchForm.page = pageNum;
    getMemberList();
};

const onSizeChange = pageSize => {
    searchForm.perPage = pageSize;
    getMemberList();
};
const searchHandler = () => {
    searchForm.page = 1;
    getMemberList();
};

const showDialog = async (type, row) => {
    dialog.type = type;
    switch (type) {
        case 1:
            dialog.title = '新增分销员';
            dialogFormData.phone = '';
            dialogFormData.id = '';
            dialogFormData.levelId = '';
            dialogFormData.inviterName = '';
            dialogFormData.type = 1;
            dialogFormData.inviterName = '';
            dialogFormData.inviterId = '';
            dialogFormData.inviterPhone = '';
            break;
        case 2:
            var { data } = await request('queryDistributorInfoServ', { id: row.id });
            dialog.title = '设置';
            dialogFormData.id = row.id;
            dialogFormData.levelId = data?.info?.levelId;
            dialogFormData.status = row.status;
            dialogFormData.inviterId = row.inviterId;
            dialogFormData.type = row.inviterId ? 2 : 1;
            dialogFormData.inviterName = row.inviterNickname;
            dialogFormData.inviterPhone = row.inviterMobile;
            dialogFormData.orginInviterName = row.inviterNickname;
            dialogFormData.orginInviterPhone = row.inviterMobile;
            break;
        case 3:
            dialogFormData.ossFileName = '';
            dialogFormData.ossFileObj = {};
            dialog.title = '批量导入分销员';
            break;
        default:
            break;
    }
    dialog.visible = true;
};

const showInviterType = () => {
    dialogFormData.type = dialogFormData.orginInviterPhone ? 2 : 1;
    dialog.inviterTypeVisible = true;
};

// 取消修改邀请人弹窗
const cancelInviterTypeDialog = () => {
    dialogFormData.inviterName = dialogFormData.orginInviterName;
    dialogFormData.inviterPhone = dialogFormData.orginInviterPhone;
    dialog.inviterTypeVisible = false;
};

// 修改邀请人弹窗确认
const comfirmInviterTypeDialog = () => {
    dialog2Form.value.validate(valid => {
        if (valid) {
            if (dialogFormData.type === 1) {
                dialogFormData.inviterName = '总部';
            }
            dialog.inviterTypeVisible = false;
        }
    });
};

const showInviterList = () => {
    chooseInviter.value.onOpen();
};

const selectInviter = val => {
    dialogFormData.inviterName = val.inviterNickname || '';
    dialogFormData.inviterPhone = val.inviterMobile || '';
    dialogFormData.inviterId = val.id || '';
};

const inviterTypeChange = val => {
    if (val === 1) {
        dialogFormData.inviterId = '';
        dialogFormData.inviterName = '';
    }
};

// 表单提交
const comfirmHandler = () => {
    dialogForm.value.validate(valid => {
        if (valid) {
            switch (dialog.type) {
                case 1:
                    addMerberHandler();
                    break;
                case 2:
                    if (dialogFormData.status == 3) {
                        confirm(`禁用之后，该分销员①不可绑定粉丝；②不可邀请分销员；③不再获得佣金；`, '', '确定禁用吗？')
                            .then(() => {
                                addMerberHandler();
                            })
                            .catch(() => {});
                    } else {
                        addMerberHandler();
                    }

                    break;
                case 3:
                    request('importDistributorServ', dialogFormData.ossFileObj).then(res => {
                        ElMessage.success(res?.data.info || '操作成功');
                        dialog.visible = false;
                        getMemberList();
                    });
                    break;
                default:
                    break;
            }
        }
    });
};

// 新增or编辑分销员
const addMerberHandler = () => {
    const para = {
        mobile: dialogFormData.phone,
        levelId: dialogFormData.levelId,
        inviterId: dialogFormData.type === 1 ? 0 : dialogFormData.inviterId,
        distributorId: dialog.type === 1 ? null : dialogFormData.id,
        status: dialog.type === 1 ? null : dialogFormData.status
    };
    const requestName = dialog.type === 1 ? 'addDistributorServ' : 'updateDistributorServ';
    request(requestName, dealObjectEmptyValue(para)).then(res => {
        ElMessage.success(`操作成功`);
        dialog.visible = false;
        getMemberList();
    });
};

// 下载模板
const downLoadTemplate = () => {
    downloadImgHandler(constants.DISTRIBUTION_TEMPLATE_URL, '分销员导入模板');
};

const uploadSuccessHandler = (res, file) => {
    dialogFormData.ossFileName = file.name;
    dialogFormData.ossFileObj = res.data?.info;
};

const deleteHandler = async row => {
    try {
        if (await confirm(`确认删除吗？`)) {
            let { id } = row;
            request('deteleDistributorServ', { id }).then(res => {
                ElMessage.success(`操作成功`);
                getMemberList();
            });
        }
    } catch (e) {}
};

// 获取分销设置
const getSetting = async row => {
    const { data } = await request('distributionSettingsInfo', {
        tab: 1
    });
    Data.inviteSwitch = Number(data.info?.inviteSwitch);
};

onMounted(() => {
    getshopList();
    getMemberList();
    getLevelList();
    getSetting();
});

onUnmounted(() => {});
</script>

<style lang="scss" scoped>
.deep_change {
    :deep(.el-tabs__header) {
        margin: 0;
    }
}
.page {
    margin-top: -24px;
    :deep {
        .el-tabs {
            --el-tabs-header-height: 60px;
        }
        .el-tabs__item {
            font-size: 16px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #35383a;
            &.is-active {
                color: #ff6b00;
            }
        }
    }
    .common {
        display: inline-block;
        width: 8px;
        height: 8px;
        background: #32d1ad;
        border-radius: 4px;
    }
    .error {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 4px;
        background: #ff4a1a;
    }
    .template {
        font-size: 14px;
        font-weight: 400;
        color: #ff6b00;
        line-height: 20px;
        margin-left: 16px;
    }
    .upload_tip {
        font-size: 12px;
        font-weight: 400;
        color: #969696;
        margin-top: 12px;
    }
    .link_btn {
        color: #ff6b00;
        cursor: pointer;
        margin-left: 16px;
    }
    .upload_file {
        margin-top: 10px;
        font-size: 14px;
        font-weight: 400;
        color: #585858;
    }
    .none {
        text-align: center;
        margin-top: 30px;
    }
}
.el-table {
    box-shadow: none;
    :deep(.el-table__empty-block) {
        border-bottom: 1px solid #eaeaea;
    }
}
</style>
